package com.aloha.springframework.beans.factory.support;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.TypeUtil;
import com.aloha.springframework.beans.BeansException;
import com.aloha.springframework.beans.PropertyValue;
import com.aloha.springframework.beans.PropertyValues;
import com.aloha.springframework.beans.factory.*;
import com.aloha.springframework.beans.factory.config.*;
import com.aloha.springframework.core.convert.ConversionService;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * @author DaiZhiHeng
 * @description 在这个抽象类中执行了具体的创建对象的方法
 * @date 2023/7/1 22:16
 */
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory {

    // 默认的创建对象的策略
    private InstantiationStrategy instantiationStrategy = new SimpleInstantiationStrategy();

    @Override
    protected Object createBean(String beanName, BeanDefinition beanDefinition, Object[] args) throws BeansException {

        // 执行 InstantiationAwareBeanPostProcessor的 Before 方法, 如果在这个方法中返回了一个对象, 后续的构建对象步骤就不会再进行了
        Object bean = resolveBeforeInstantiation(beanName, beanDefinition);
        if (bean != null) return bean;

        return doCreateBean(beanName, beanDefinition, args);
    }

    /**
     * 创建对象时更加细粒度的控制
     */
    protected Object doCreateBean(String beanName, BeanDefinition beanDefinition, Object[] args) {
        Object bean, exposedObject;
        try {
            // 创建Bean实例
            bean = createBeanInstance(beanName, beanDefinition, args);

            // 解决对象的循环依赖问题, 将刚刚创建好的但是尚未给属性赋值的对象提前暴露
            if (beanDefinition.isSingleton()) {
                addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, beanDefinition, bean));
            }

            // 执行 InstantiationAwareBeanPostProcessor的 After 方法, 如果返回false后续操作不会再执行
            if (!applyBeanPostProcessorsAfterInstantiation(beanName, bean)) return bean;

            // 执行 InstantiationAwareBeanPostProcessor的 postProcessPropertyValues() 方法, 可以修改将要填充
            applyBeanPostprocessorsBeforeApplyingPropertyValues(beanName, bean, beanDefinition);

            exposedObject = bean;
            // 给 Bean 填充属性
            applyPropertyValues(beanName, beanDefinition, exposedObject);
            // 执行 Bean 的初始化方法和 BeanPostProcessor 的前置和后置处理方法
            exposedObject = initializeBean(beanName, beanDefinition, exposedObject);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BeansException("初始化Bean失败", e);
        }

        if (beanDefinition.isSingleton()) {
            // 如果没有发生循环依赖返回值是null
            Object earlySingletonReference = getSingleton(beanName, false);
            if (earlySingletonReference != null) { // 发生了循环依赖
                if (exposedObject == bean) { // 初始化阶段未创建代理，表明发生过循环依赖，代理对象目前在二级缓存中
                    exposedObject = earlySingletonReference;
                }
            }
            registerSingleton(beanName, exposedObject);
        }

        // 注册实现了 DisposableBean 接口的 Bean 对象
        registerDisposableBeanIfNecessary(beanName, beanDefinition, bean);

        return exposedObject;
    }

    protected Object resolveBeforeInstantiation(String beanName, BeanDefinition beanDefinition) {
        Object bean = applyBeanPostProcessorsBeforeInstantiation(beanDefinition.getBeanClass(), beanName);
        if (bean != null) {
            bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
        }
        return bean;
    }

    protected Object applyBeanPostProcessorsBeforeInstantiation(Class<?> beanClass, String beanName) {
        for (BeanPostProcessor beanPostProcessor : getBeanPostProcessors()) {
            if (!(beanPostProcessor instanceof InstantiationAwareBeanPostProcessor)) continue;
            Object result = ((InstantiationAwareBeanPostProcessor) beanPostProcessor).postProcessBeforeInstantiation(beanClass, beanName);
            if (result != null) return result;
        }
        return null;
    }

    protected Object getEarlyBeanReference(String beanName, BeanDefinition beanDefinition, Object bean) {
        Object exposedObject = bean;
        for (BeanPostProcessor bp : getBeanPostProcessors()) {
            if (!(bp instanceof SmartInstantiationAwareBeanPostProcessor)) continue;
            exposedObject = ((SmartInstantiationAwareBeanPostProcessor) bp).getEarlyBeanReference(exposedObject, beanName);
            if (exposedObject == null) return null;
        }
        return exposedObject;
    }

    /**
     * bean实例化后执行，如果返回false，不执行后续的后置处理器
     */
    private boolean applyBeanPostProcessorsAfterInstantiation(String beanName, Object bean) {
        boolean continueWithPropertyPopulation = true;
        for (BeanPostProcessor beanPostProcessor : getBeanPostProcessors()) {
            if (!(beanPostProcessor instanceof InstantiationAwareBeanPostProcessor)) continue;
            boolean applyBeanPostProcessor = ((InstantiationAwareBeanPostProcessor) beanPostProcessor).postProcessAfterInstantiation(bean, beanName);
            if (applyBeanPostProcessor) continue;
            continueWithPropertyPopulation = false;
            break;
        }
        return continueWithPropertyPopulation;
    }

    /**
     * 在设置bean属性之前，允许InstantiationAwareBeanPostProcessor修改属性值
     */
    protected void applyBeanPostprocessorsBeforeApplyingPropertyValues(String beanName, Object bean, BeanDefinition beanDefinition) {
        for (BeanPostProcessor beanPostProcessor : getBeanPostProcessors()) {
            if (!(beanPostProcessor instanceof InstantiationAwareBeanPostProcessor)) continue;
            PropertyValues propertyValues = ((InstantiationAwareBeanPostProcessor) beanPostProcessor).postProcessPropertyValues(beanDefinition.getPropertyValues(), bean, beanName);
            if (propertyValues == null) continue;
            for (PropertyValue propertyValue : propertyValues.getPropertyValues()) {
                beanDefinition.getPropertyValues().addPropertyValue(propertyValue);
            }
        }
    }

    /**
     * 创建对象实例
     */
    protected Object createBeanInstance(String beanName, BeanDefinition beanDefinition, Object[] args) {
        Constructor<?> constructorToUse = null;
        Class<?> beanClass = beanDefinition.getBeanClass();
        Constructor<?>[] declaredConstructors = beanClass.getDeclaredConstructors();

        // 遍历所有的构造器，找到一个符合条件的就退出
        for (Constructor<?> constructor : declaredConstructors) {
            if (args != null && constructor.getParameterTypes().length == args.length) {
                constructorToUse = constructor;
                break;
            }
        }
        // 如果未找到，constructorToUse就为null，后续就会使用无参构造器创建对象
        return getInstantiationStrategy().instantiate(beanName, beanDefinition, constructorToUse, args);
    }

    /**
     * 注册后置处理器
     */
    protected void registerDisposableBeanIfNecessary(String beanName, BeanDefinition beanDefinition, Object bean) {
        // 非单例的对象不需要注册销毁方法
        if (!beanDefinition.isSingleton()) return;

        // 一个bean对象实现了DisposableBean方法或者提供了销毁方法
        if (bean instanceof DisposableBean || StrUtil.isNotEmpty(beanDefinition.getDestroyMethodName())) {
            registerDisposableBean(beanName, new DisposableBeanAdapter(bean, beanName, beanDefinition));
        }
    }

    /**
     * Bean 属性填充
     */
    protected void applyPropertyValues(String beanName, BeanDefinition beanDefinition, Object bean) {
        try {
            PropertyValues propertyValues = beanDefinition.getPropertyValues();
            for (PropertyValue propertyValue : propertyValues.getPropertyValues()) {

                String name = propertyValue.getName();
                Object value = propertyValue.getValue();

                if (value instanceof BeanReference) {
                    // 当前bean的某个属性是容器中的某个bean
                    BeanReference beanReference = (BeanReference) value;
                    value = getBean(beanReference.getBeanName());
                } else {
                    //类型转换
                    Class<?> sourceType = value.getClass();
                    Class<?> targetType = (Class<?>) TypeUtil.getFieldType(bean.getClass(), name);
                    ConversionService conversionService = getConversionService();
                    if (conversionService != null) {
                        if (conversionService.canConvert(sourceType, targetType)) {
                            value = conversionService.convert(value, targetType);
                        }
                    }
                }
                // 属性填充
                BeanUtil.setFieldValue(bean, name, value);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BeansException("填充属性时出错：" + beanName);
        }
    }

    /**
     * 初始化方法
     */
    private Object initializeBean(String beanName, BeanDefinition beanDefinition, Object bean) {
        // 执行Aware感知器接口的方法
        invokeAwareMethods(beanName, beanDefinition, bean);

        // 后置处理器的before方法
        bean = applyBeanPostProcessorsBeforeInitialization(bean, beanName);

        // 执行初始化方法
        try {
            invokeInitMethods(beanName, bean, beanDefinition);
        } catch (Exception e) {
            throw new BeansException("[" + beanName + "] 在执行初始化方法时出错", e);
        }

        // 后置处理器的after方法
        return applyBeanPostProcessorsAfterInitialization(bean, beanName);
    }

    /**
     * 调用 Aware 感知器接口的方法
     */
    private void invokeAwareMethods(String beanName, BeanDefinition beanDefinition, Object bean) {
        if (bean instanceof Aware) {
            if (bean instanceof BeanFactoryAware) {
                ((BeanFactoryAware) bean).setBeanFactory(this);
            }
            if (bean instanceof BeanClassLoaderAware) {
                ((BeanClassLoaderAware) bean).setBeanClassLoader(getBeanClassLoader());
            }
            if (bean instanceof BeanNameAware) {
                ((BeanNameAware) bean).setBeanName(beanName);
            }
        }
    }

    /**
     * 调用初始化方法
     */
    private void invokeInitMethods(String beanName, Object bean, BeanDefinition beanDefinition) throws Exception {
        // 实现 InitializingBean接口的bean
        if (bean instanceof InitializingBean) {
            ((InitializingBean) bean).afterPropertiesSet();
        }

        // init-method
        String initMethodName = beanDefinition.getInitMethodName();
        if (StrUtil.isNotEmpty(initMethodName)) {
            try {
                Method initMethod = beanDefinition.getBeanClass().getMethod(initMethodName);
                initMethod.invoke(bean);
            } catch (Exception exception) {
                throw new BeansException("在 [" + beanName + "] 中未找到名为 [" + initMethodName + "] 的初始化方法");
            }
        }
    }

    @Override
    public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName) throws BeansException {
        Object result = existingBean;
        for (BeanPostProcessor processor : getBeanPostProcessors()) {
            Object current = processor.postProcessBeforeInitialization(result, beanName);
            if (current == null) return result;
            result = current;
        }
        return result;
    }

    @Override
    public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName) throws BeansException {
        Object result = existingBean;
        for (BeanPostProcessor processor : getBeanPostProcessors()) {
            Object current = processor.postProcessAfterInitialization(result, beanName);
            if (current == null) return result;
            result = current;
        }
        return result;
    }

    public InstantiationStrategy getInstantiationStrategy() {
        return instantiationStrategy;
    }

    public void setInstantiationStrategy(InstantiationStrategy instantiationStrategy) {
        this.instantiationStrategy = instantiationStrategy;
    }
}
